// 把参数放在一个对象里方便复用
const query = {
  sex: '',
  username: '',
  mobile: '',
  page: 1,
  limit: 10,
}


//todo ============================获取用户信息数据===========================
getList()
function getList() {
  let arr = []
  const x_token = localStorage.getItem('x-token')
  axios.get('http://124.223.14.236:8060/admin/ydd_user/list', { params: query })
    .then((res) => {
      // console.log(res)


      // console.log(res.data.data.data)
      let newArr = res.data.data.data.map((item, index) => {

        arr.push(item.sex)
        if (arr[index] === 0) {
          arr[index] = '男'
        } else {
          arr[index] = '女'
        }
        return `
                <tr>
                <td>${index + 1}</td>
                <td>${item.id}</td>
                <td>${item.username}</td>
                <td>${item.mobile}</td>
                <td><img src="http://124.223.14.236:8060/${item.icon}" alt=""></td>
                <td>${arr[index]}</td>
                <td>2023-06-29</td>
                <td>已发布</td>
                <td>
                  <button type="button" class="layui-btn layui-btn-normal btn_edit w_circle1" data-id=${item.id}>
                    <i class="layui-icon layui-icon-edit w_pen" style="font-size: 18px;" ></i>
                  </button>
                  <button type="button" class="layui-btn layui-btn-xs layui-btn-danger btn_delete w_circle1">
                    <i class="layui-icon layui-icon-delete w_bin" data-id=${item.id}></i>
                  </button>
                </td>
              </tr>
        `
      })
      $('#tbody').html(newArr.join(''))
      renderPage(res.data.data.count)
    })
}



const laypage = layui.laypage;

function renderPage(total) {
  //执行一个laypage实例
  laypage.render({
    elem: 'page-box',//注意，这里的 test1 是 ID，不用加 # 号
    count: total, //数据总数，从服务端得到
    curr: query.page, //当前第几页（会决定第几个按钮是高亮）
    limits: [1, 2, 3, 4, 5, 10], //下拉框每一项的结果
    limit: query.limit, // 每页显示的条数
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], //排版
    jump: function (obj, first) {
      // jump的触发时机：
      //1.当laypage.render 分页渲染的时候，会触发该回调函数
      //2.当分页切换的时候会触发该回调函数

      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数

      //完成切换分页效果 ===> 核心就是发ajax请求
      query.page = obj.curr
      query.limit = obj.limit
      // console.log(query)

      // 发Ajax请求
      // getList() //代码这样一写就出问题（不停的发ajax请求）


      //首次不执行
      if (!first) {
        // if 成立说明first 的值是 undefind,是点击分页切换来触发的
        getList()
      }
    }
  });
}


//todo============================删除========================================
document.querySelector('#tbody').addEventListener('click', function (e) {
  if (e.target.classList.contains('w_bin')) {
    const id = e.target.dataset.id
    console.log(id)
    const x_token = localStorage.getItem('x-token')
    axios.get(`http://124.223.14.236:8060/admin/ydd_user/del?id=${id}`, { params: { x_token } })
      .then(res => {
        console.log(res)
        layer.msg('删除成功');
        // layer.confirm('确定删除吗？', {
        //     btn: ['确定', '取消'] //按钮
        // }, function () {
        //     layer.msg('删除成功', { icon: 1 });
        // }),
        getList()
      })
  }
})



// todo ========== 添加功能 ==============================================
const layer = layui.layer
const form = layui.form
const addFormStr =
  `
<form class="layui-form formIfm" action="" id="addForm">
        <div class="layui-form-item">
          <div class="layui-col-md5">
            <label class="layui-form-label"><strong>*</strong>用户名</label>
            <div class="layui-input-block">
              <input type="text" name="username" id="username" lay-verify="required" placeholder="请输入标题" autocomplete="off"
                class="layui-input">
            </div>
          </div>
  
          <div class="layui-col-md5">
            <div class="cate">
              <label class="layui-form-label"><strong>*</strong>手机号</label>
              <div class="layui-input-block">
                <input type="text" name="mobile" id="mobile" lay-verify="required" placeholder="手机号" autocomplete="off"
                  class="layui-input">
              </div>

            </div>
          </div>
        </div>



        <div class="layui-form-item">

          <div class="layui-col-md3">
            <div class="cate" id="w-psw-box">
              <label class="layui-form-label"><strong>*</strong>密码</label>
              <div class="layui-input-block">
                <input type="text" name="password" id="password" lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
          </div>
          
          <div class="layui-col-md5" id="gender">
            <label class="layui-form-label"><strong>*</strong>性别</label>
            <span class="nan">男</span>
            <div class="layui-input-inline" id="w-check-box">
              <input type="checkbox" name="sex" id="sex1" lay-skin="switch" class="gender-checked">
            </div>
            <span class="nv">女</span>
          </div>

        </div>

        <div class="layui-form-item">
          <label class="layui-form-label"><strong>*</strong>上传头像</label>
          <button type="button" class="layui-btn w-dome-tx" id="ID-upload-demo-btn">
            <i class="layui-icon layui-icon-upload"></i> 点击上传
          </button>

          <input type="file" id="fileAdd" style="display: none;">

          <!-- 上传图片显示 -->
          <div style="width: 220px;margin-left: 110px;">
            <div class="layui-upload-list">
              <img class="layui-upload-img" id="addImg" style="width: 100%; height: 92px;">
              <div id="ID-upload-demo-text"></div>
            </div>
          
          </div>

        </div>

        <div class="layui-form-item" >
          <div class="layui-input-block" id="w-btn">
            <button type="button" class="layui-btn layui-btn-normal" id="w-quxiao">取消</button>
            <button type="submit" class="layui-btn layui-btn-warm">确认</button>
          </div>
        </div>
      </form>
`
let addFormIndex
$('#btnAddCate').on('click', function () {
  addFormIndex = layer.open({
    title: '添加用户', //标题
    content: addFormStr, // 内容
    type: 1, // 类型
    area: ['640px', '407px'], // 宽高

  })
  form.render()
})

// todo ========添加=========点击好看的按钮  模拟点击文件域===========================
$('body').on('click', '#ID-upload-demo-btn', function () {
  // 模拟点击文件选择框
  $('#fileAdd').click()
})

let fileUrl
$('body').on('change', '#fileAdd', function () {
  const files = this.files[0]
  const fd = new FormData()
  fd.append('file', files)

  //// axios.defaults.headers['Content-Type'] = 'multipart/form-data'
  axios.post('/common/upload?type=images', fd).then(({ data: { data: { savePath } } }) => {
    $('#addImg').prop("src", `http://124.223.14.236:8060/${savePath}`)
    fileUrl = savePath
  })
})


// todo 添加信息成功
$('body').on('submit', '#addForm', function (e) {
  e.preventDefault()
  // console.log(11)
  const username = $('#username').val()
  const mobile = $('#mobile').val()
  let sex = $('#sex1').prop('checked')
  const psd = $('#password').val()
  const imgSrc = fileUrl
  console.log(sex);
  sex = sex ? 1 : 0
  
  
  // 获取到表单数据，提交
  // let data = $(this).serialize()
  // console.log(data)
  // const icon = $('#addImg').prop("src").split('8060/')[1]
  // console.log(icon);
  // data = data +`&icon=${icon}`
  // console.log(data);


  axios.post("/ydd_user/add", {
    icon: imgSrc,
    mobile: mobile,
    password: psd,
    sex: sex,
    username: username

  }).then((res) => {
    console.log(res)
    // if (res.data.status !== 0) {
    //     // 失败
    //     return layer.msg(res.data.message)
    // }

    // 新增成功之后，还要做的事
    // 1. 关闭弹出层
    layer.close(addFormIndex)

    // 2. 重新获取所有的分类数据渲染展示到页面中
    getList()

    // 3. 提示成功
    layer.msg('添加成功');
  })

})

//todo ====================取消功能===========================================

$('body').on('click', '#w-quxiao', function () {
  layer.close(addFormIndex)
})

//todo ====================编辑功能==========================================
const editFormStr = `
<form class="layui-form formIfm" action="" id="editForm" lay-filter="editForm">
        <div class="layui-form-item">

        <div class="layui-col-md5 layui-hide">
        <div class="cate">
          <label class="layui-form-label"><strong>*</strong>id</label>
          <div class="layui-input-block">
            <input type="text" name="id" lay-verify="required" placeholder="id" autocomplete="off"
              class="layui-input">
          </div>
        </div>
      </div>

          <div class="layui-col-md5">
            <label class="layui-form-label"><strong>*</strong>用户名</label>
            <div class="layui-input-block">
              <input type="text" name="username" lay-verify="required" placeholder="请输入标题" autocomplete="off"
                class="layui-input">
            </div>
          </div>
          <div class="layui-col-md5">
            <div class="cate">
              <label class="layui-form-label"><strong>*</strong>手机号</label>
              <div class="layui-input-block">
                <input type="text" name="mobile" lay-verify="required" placeholder="手机号" autocomplete="off"
                  class="layui-input">
              </div>

            </div>
          </div>
        </div>



        <div class="layui-form-item">

          <div class="layui-col-md5">
            <div class="cate" id="w-psw-box">
              <label class="layui-form-label"><strong>*</strong>密码</label>
              <div class="layui-input-block">
                <input type="text" name="password" lay-verify="required" placeholder="请输入标题" autocomplete="off"
                  class="layui-input">
              </div>
            </div>
          </div>
          
          <div class="layui-col-md5 sex" id="gender">
            <label class="layui-form-label"><strong>*</strong>性别</label>
            <span class="nan">男</span>
            <div class="layui-input-inline" id="w-check-box">
              <input type="checkbox" name="sex" id="sex2" lay-skin="switch" class="gender-checked">
            </div>
            <span class="nv">女</span>
          </div>

        </div>

        <div class="layui-form-item">
          <label class="layui-form-label"><strong>*</strong>上传头像</label>
          <button type="button" class="layui-btn w-dome-tx" id="ID-upload-demo-btn">
            <i class="layui-icon layui-icon-upload"></i> 点击上传
          </button>

          <input type="file" id="fileEdit" style="display: none;">

          <!-- 上传图片显示 -->
          <div style="width: 220px;margin-left: 110px;">
            <div class="layui-upload-list">
              <img  class="layui-upload-img editImg" id="ID-upload-demo-img" style="width: 100%; height: 125px;">
              <div id="ID-upload-demo-text"></div>
            </div>
          </div>

        </div>

        <div class="layui-form-item" >
          <div class="layui-input-block" id="w-btn">
            <button type="button" class="layui-btn layui-btn-normal" id="y-quxiao">取消</button>
            <button type="submit" class="layui-btn layui-btn-warm">确认</button>
          </div>
        </div>
      </form>
`
let EditFormIndex
let imgSrc
$('body').on('click', '.btn_edit', function () {
  $('.editImg').prop('src', '')
  const id = $(this).attr('data-id')
  // console.log(id)

  //发送ajax 请求获取到对应数据，填充到表单中
  axios.get(`/ydd_user/rowInfo?id=${id}`).then(({ data }) => {
    // console.log(data.data);

    //给表单赋值
    //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
    form.val('editForm', data.data);
    imgSrc = data.data.icon
    if(imgSrc) $('.editImg').prop('src', `http://124.223.14.236:8060/${imgSrc}`)
    
  })


  // 编辑弹出框

  EditFormIndex = layer.open({
    title: '修改用户', //标题
    content: editFormStr, // 内容
    type: 1, // 类型
    area: ['640px', '400px'], // 宽高
  })
  form.render()
})

// todo ==========修改=======点击好看的按钮  模拟点击文件域===========================
$('body').on('click', '#ID-upload-demo-btn', function () {
  // 模拟点击文件选择框
  $('#fileEdit').click()
})

let imgUrl
$('body').on('change', '#fileEdit', function () {
  const files = this.files[0]
  const fd = new FormData()
  fd.append('file', files)

  axios.defaults.headers['Content-Type'] = 'multipart/form-data'// 默认请求头设置
  axios.post('/common/upload?type=images', fd).then(({ data: { data: { savePath } } }) => {
    $('.editImg').prop("src", `http://124.223.14.236:8060/${savePath}`)
    imgUrl = savePath
  })
})

// todo ===============确认修改=================================================
$('body').on('submit', '#editForm', function (e) {
  e.preventDefault()
  // 获取到表单数据，提交
  const fd = new FormData(this)
  let sex = $('#sex2').prop('checked')
 fd.forEach(function(item,name){
  console.log(item,name);
 })
  sex = sex ? 1 : 0
  console.log(sex);
  fd.append('icon', imgSrc)
  fd.set('sex',sex)
  if(imgUrl){
    fd.set('icon',imgUrl)
  }
  

  axios.post('/ydd_user/update', fd).then(({ data }) => {
    $('.editImg').prop('src', '')

    // 提示成功
    layer.msg('更新成功');

    // 重新获取所有的分类数据渲染展示到页面中
    getList()
    // if (data.status !== 0) {
    //     // 失败
    //     return layer.msg(data.message)
    // }

    // 新增成功之后，还要做的事
    //  关闭弹出层
    layer.close(EditFormIndex)
  })
})

// todo ========================取消功能=======================================
$('body').on('click', '#y-quxiao', function () {
  layer.close(EditFormIndex)
})


//todo ================搜索功能===============================================

$('#search').on('click', function () {
  // 先需要处理好id
  const username = $('.username').val()
  const mobile = $('.mobile').val()
  const sex = $('#sex').val()


  console.log(sex);
  let arr = []

  //发送ajax 请求获取到对应数据，填充到表单中
  axios.get(`http://124.223.14.236:8060/admin/ydd_user/list?username=${username}&mobile=${mobile}&sex=${sex}`).then(({ data }) => {
    console.log(data);

    let newArr = data.data.data.map((item, index) => {

      arr.push(item.sex)
      if (arr[index] === 0) {
        arr[index] = '男'
      } else {
        arr[index] = '女'
      }
      return `
            <tr>
            <td>${index + 1}</td>
            <td>${item.id}</td>
            <td>${item.username}</td>
            <td>${item.mobile}</td>
            <td><img src="http://124.223.14.236:8060/${item.icon}" alt=""></td>
            <td>${arr[index]}</td>
            <td>2023-06-29</td>
            <td>已发布</td>
            <td>
              <button type="button" class="layui-btn layui-btn-normal btn_edit w_circle1" data-id=${item.id}>
                <i class="layui-icon layui-icon-edit w_pen" style="font-size: 18px;" ></i>
              </button>
              <button type="button" class="layui-btn layui-btn-xs layui-btn-danger btn_delete w_circle1">
                <i class="layui-icon layui-icon-delete w_bin" data-id=${item.id}></i>
              </button>
            </td>
          </tr>
    `
    })
    $('#tbody').html(newArr.join(''))
  })

  $('#reset').click()
})

//todo ==========================关闭搜索区=======================================

$('#close').on('click', function () {
  $('#w-header').toggle()
})

//todo ==========================刷新============================================
$('#shuaxin').on('click', function () {
  self.location.reload()
})